package com.zlb.app.common.strategy.impl;

import com.zlb.app.common.exception.BusinessException;
import com.zlb.app.common.strategy.UploadStrategy;
import com.zlb.app.utils.FileUtil;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @Desc 上传策略实现-抽象实现,
 * @Author zWX1367238
 * @Date 2024-08-16 10:49:13
 **/
public abstract class AbstractUploadStrategyImpl implements UploadStrategy {

    @Override
    public String uploadFile(MultipartFile file, String folder) {
        try {
            // 重置文件名
            // String md5 = FileUtil.getMd5(file.getInputStream());
            String extName = FileUtil.getExtName(file.getOriginalFilename());
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String fileName = uuid + extName;
            if (!exists(folder + fileName)) {
                upload(folder, fileName, file.getInputStream());
            }
            return getFileAccessUrl(folder + fileName);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("文件上传失败");
        }
    }

    @Override
    public String uploadFile(String fileName, InputStream inputStream, String folder) {
        try {
            upload(folder, fileName, inputStream);
            return getFileAccessUrl(folder + fileName);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("文件上传失败");
        }
    }

    /**
     * 策略模式抽象判断存在方法,子类实现
     * @param filePath
     * @return
     */
    public abstract Boolean exists(String filePath);

    /**
     * 策略模式抽象上传方法,子类实现
     * @param folder 文件保存在哪个文件夹
     * @param fileName 文件名称
     * @param inputStream 流
     * @throws IOException 异常
     */
    public abstract void upload(String folder, String fileName, InputStream inputStream) throws IOException;

    /**
     * 策略模式抽象获取文件地址方法,子类实现
     * @param filePath 设置的文件保存地址+文件名称
     * @return 完整的文件保存地址
     */
    public abstract String getFileAccessUrl(String filePath);

}
